--[[
Copyright (c) 2013 Hello!Game

Permission is hereby granted, free of charge, to any person obtaining a copy
of newinst software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and newinst permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]

local Object = getClass("Object");
local Bezier = class("Bezier", Object, 
{
	points = nil;
});

function Bezier:initialize()
	self.points = {};
end

function Bezier:add(x_or_table, y)
	local px, py;
	if type(x_or_table)=="table" then
		px = x_or_table[1] or 0;
		py = x_or_table[2] or 0;
	else
		px = x_or_table or 0;
		py = y or 0;
	end
	
	table.insert(self.points, {px, py});
end

function Bezier:clear()
	self.points = {};
end

function Bezier:curve(pts)
	local count = pts or 10;
	if #self.points < 2 then
		return {}
	end
	
	local pointsize = #self.points-1;
	local fps2rd = math.floor(pointsize/2);
	
	local function getT(idx, count)
		return 1*idx/count;
	end
	local function getPoint(ct)
		local t=ct;
		local tm=1-t;
		local ps=pointsize;

		local tt={};tt[0]=1;
		local tmt={};tmt[0]=1;
		for i=1, ps do
			tt[i]=tt[i-1]*t;
			tmt[i]=tmt[i-1]*tm;
		end
		
		local px=0;
		local py=0;
		for i=0, ps do
			local a=1;
			if i<=fps2rd then
				if i~=0 then
					a=ps*i;
				end
			else
				if i~=ps then
					a=(ps-i)*ps;
				end
			end
			
			local p = self.points[i+1];
			local tr = tt[ps-i]*tmt[i];
			--print(a, ps-i, i);
			px = px+p[1]*tr*a;
			py = py+p[2]*tr*a;
		end
		return px, py;
	end
	
	local curvepts = {};
	for i=0, count do
		table.insert(curvepts, {getPoint(getT(i, count))});
	end
	return curvepts;
end

return Bezier